<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    width="80%"
    top="5%"
  >
    <div style="height: 50vh">
          <div v-if="rowIndex==null">
            <t-alert  style="margin-bottom: 20px" theme="info" :message="`当前页面可重复添加。目前已添加数量: ${data.length}`"/>
          </div>

      <t-form ref="form" resetType="initial" :data="formData" labelWidth="160px" :rules="rules">
        <t-row style="row-gap:24px">
          <t-col :span="6">
            <t-form-item label="姓名" name="name">
              <t-select
                v-model="formData.name"
                creatable
                filterable
                @change="onLeaderNameChange"
                placeholder="请输入姓名"
                :loading="nameLoading"
                @search="remoteNameMethod"
                :options="nameOptions"
                @create="createNameOptions"
                style="width: 390px"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="身份证号" name="idCard">
              <t-input style="width: 390px" @change="onIdCardChange" placeholder="请输入身份证号" clearable
                       v-model="formData.idCard"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="手机号码" name="phone">
              <t-input clearable style="width: 390px" v-model="formData.phone" :maxlength="11"
                       placeholder="请输入手机号码"></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="邮箱" name="email">
              <t-input clearable style="width: 390px" v-model="formData.email" :maxlength="50"
                       placeholder="请输入邮箱"></t-input>
            </t-form-item>
          </t-col>
          <!--          <t-col :span="6">-->
          <!--            <t-form-item label="出生年月" name="birthDate">-->
          <!--              <t-date-picker-->
          <!--                disabled-->
          <!--                :disable-date="{-->
          <!--        after: dayjs().endOf('month').add(-18, 'year').format()}"-->
          <!--                clearable allow-input-->
          <!--                style="width: 390px"-->
          <!--                mode="month"-->
          <!--                v-model="formData.birthDate"></t-date-picker>-->
          <!--            </t-form-item>-->
          <!--          </t-col>-->
          <!--          <t-col :span="6">-->
          <!--            <t-form-item label="性别" name="sex">-->
          <!--              <t-select clearable style="width:390px" :options="dict.type.sys_user_sex"-->
          <!--                        v-model="formData.sex"></t-select>-->
          <!--            </t-form-item>-->
          <!--          </t-col>-->
          <t-col :span="6">
            <t-form-item label="职务" name="duty">
              <t-input clearable style="width:390px" v-model="formData.duty"
              ></t-input>
            </t-form-item>
          </t-col>
          <!--          <t-col :span="6">-->
          <!--            <t-form-item label="学历" name="education">-->
          <!--              <t-select style="width: 390px" v-model="formData.education" clearable-->
          <!--                        placeholder="请选择学历"-->
          <!--                        :options="dict.type.education">-->
          <!--              </t-select>-->
          <!--            </t-form-item>-->
          <!--          </t-col>-->
          <t-col :span="6">
            <t-form-item label="技术职称" name="profTitId">
              <t-tree-select style="width:390px" @change="onProfTitIdChange" clearable filterable
                             :treeProps="{keys: {value: 'id',label:'name'}, valueMode: 'onlyLeaf'}"
                             v-model="formData.profTitId" :data="profTitOptions" placeholder="技术职称"></t-tree-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="职称" name="profTit">
              <t-select disabled style="width:390px" v-model="formData.profTit" clearable placeholder="请选择职称"
                        :options="dict.type.prof_tit"></t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="所在单位" help="搜索不到请切换外部单位后手输" name="company">
              <t-tree-select v-if="formData.isInnerCompany==='1'" style="width:390px" clearable filterable
                             :treeProps="{keys: {value: 'label'}}" v-model="formData.company" :data="deptMenuOptions"
                             placeholder="选择单位">
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="formData.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{formData.company=''}"
                  ></t-switch>
                </template>
              </t-tree-select>
              <t-select
                v-else
                v-model="formData.company"
                creatable
                filterable
                placeholder="请输入"
                :loading="companyLoading"
                @search="remoteCompanyMethod"
                :options="companyOptions"
                @create="createCompanyOptions"
                style="width: 390px"
              >
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="formData.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{formData.company=''}"
                  ></t-switch>
                </template>
              </t-select>
            </t-form-item>
          </t-col>
          <!--          <t-col :span="6">-->
          <!--            <t-form-item label="在本项目中承担的任务" name="task">-->
          <!--              <t-input style="width:390px" clearable v-model="formData.task" placeholder="请输入"></t-input>-->
          <!--            </t-form-item>-->
          <!--          </t-col>-->
        </t-row>
      </t-form>
    </div>
    <template #footer>
      <t-button theme="default" @click="closeDialog">取消</t-button>
      <t-button theme="primary" @click="onSubmit(1)">保存</t-button>
      <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>
    </template>
  </t-dialog>
</template>

<script>
import {getIdCardBirthday, getIdCardAge} from '@/utils/common';
import dayjs from "dayjs"

export default {
  name: "add-edit-member",
  props: ['header', "editOpen", "oldData", "rowIndex","data"],
  dicts: ["sys_user_sex", "education", "prof_tit"],
  data() {
    return {
      deptMenuOptions: [],
      profTitOptions: [],
      companyLoading: false,
      companyOptions: [],
      nameLoading: false,
      nameOptions: [],
      visible: true,
      dayjs,
      rules: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
          }
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          }
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不能为空",
          }
        ],
        duty: [
          {
            required: true,
            message: "职务不能为空",
          }
        ],
        profTit: [
          {
            required: true,
            message: "职称不能为空",
          }
        ],
        profTitId: [
          {
            required: true,
            message: "技术职称不能为空",
          }
        ],
        education: [{
          required: true,
          message: "学历不能为空",
        }],
        majorName: [
          {
            required: true,
            message: "所学专业不能为空",
          }
        ],
        majorNowName: [
          {
            required: true,
            message: "现从事专业不能为空",
          }
        ],
        company: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        task: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        isInnerCompany: [
          {
            required: true,
            message: "不能为空",
          }
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        phone: [
          {
            required: true,
            message: "手机号不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空",
          },
          {email: {ignore_max_length: true}, message: '请输入正确的邮箱地址'}
        ],
      },
      formData: {
        phone: '',
        email: '',
        name: '',
        sex: '',
        birthDate: '',
        duty: '',
        profTit: '',
        profTitId: null,
        majorName: '',
        majorNowName: '',
        company: '',
        task: '',
        education: '',
        idCard: '',
        isAssist: '0',
        isInnerCompany: '1'
      },
    }
  },
  watch: {
    oldData: {
      immediate: true,
      deep: true,
      handler(val) {
        Object.assign(this.formData, val)
      }
    },
    rowIndex: {
      immediate: true,
      handler(val) {
      }
    }
  },
  created() {
    this.getProfTitTreeSelect();
    this.getDeptTreeSelect();
  },
  methods: {
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect() {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== "") {
        this.formData.birthDate = birthday.slice(0, 7)
      }
    },
    createCompanyOptions(value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod(search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName: search}).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange(val, content) {
      const index = this.nameOptions.findIndex(val => content.option?.id === val.id)
      this.nameOptions[index].label = this.nameOptions[index].name;
      this.$set(this.nameOptions, index, this.nameOptions[index])
      Object.assign(this.formData, content.option || this.nameOptions[index])
    },
    createNameOptions(value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteNameMethod(search) {
      this.nameLoading = true;
      this.$api.system.member.searchList({name: search}).then(response => {
        this.nameOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.nameLoading = false;
      }).catch((e) => {
        this.nameLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit(type) {
      // 深拷贝
      const newData = {...this.formData};
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          if (this.editOpen) {
            this.$emit("updateData", newData,this.rowIndex);
            this.$refs.form.reset();
            if (type === 1) {
              this.closeDialog()
            }
          } else {
            this.$emit("addData", newData);
            this.$refs.form.reset();
            if (type === 1) {
              this.closeDialog()
            }
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    closeDialog() {
      // this.$refs.form.reset();
      this.$emit("update:visible", false);
    },
  }
}
</script>

<style scoped>

</style>
